﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using BEGDC.CC.BL.Common;
using BEGDC.CC.BL.Common.Query;
using BEGDC.CC.BL.UserManagement;
using BEGDC.CC.BL.Workflow;
using BEGDC.CC.Entity;
using BEGDC.CC.Web.UserControls;
using BEGDC.Utility.Castle;
using BEGDC.Utility.ExceptionManagement;
using NetBpm.Util.Client;
using NetBpm.Workflow.Execution;
using NetBpm.Workflow.Execution.EComp;

namespace BEGDC.CC.Web
{
    /// <summary>
    /// Summary description for main.
    /// </summary>
    public class DelegationManagement : System.Web.UI.Page
    {
        /// <summary>
        /// 
        /// </summary>
        private string _SelectedUser
        {
            get
            {
                if (Session["_SelectedUser"] == null) return string.Empty;

                return (string)(Session["_SelectedUser"]);
            }
            set { Session["_SelectedUser"] = value; }
        }

        protected System.Web.UI.WebControls.DataGrid dgRoles;
        protected BEGDC.CC.Web.Control.UserSearchControl SearchStaff;
        protected System.Web.UI.WebControls.Button btnSearch;
        protected System.Web.UI.WebControls.DataGrid dgDelegated;
        protected System.Web.UI.WebControls.LinkButton LinkButton1;

        private void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                // Put user code to initialize the page here
                if (!Page.IsPostBack)
                {
                    if (_SelectedUser != string.Empty)
                    {
                        IUser iuser = AppContainer.Instance[ServiceConst.UserService] as IUser;
                        BEGDC.CC.Entity.Employee employee = iuser.GetUserByID(this._SelectedUser);
                        this.SearchStaff.EmployeeID = _SelectedUser;
                        this.SearchStaff.EmployeeName = employee.NameEN;
                    }
                    this.BindData();
                }

            }
            catch (GDCException gdcEx)
            {
                WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
            }
        }

        private void BindData()
        {
            string employeeid = this.SearchStaff.EmployeeID;
            IQuery iquery = AppContainer.Instance[ServiceConst.QueryService] as IQuery;

            System.Data.DataTable dtRoles = iquery.QueryRoleList(employeeid);

            this.dgRoles.DataSource = dtRoles;
            this.dgRoles.DataBind();


            System.Data.DataTable dtDelegates = iquery.QueryDelegatedList(employeeid);

            this.dgDelegated.DataSource = dtDelegates;
            this.dgDelegated.DataBind();

        }


        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.dgRoles.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgRoles_ItemDataBound);
            this.dgRoles.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgRoles_ItemCommand);

            this.btnSearch.Click += new EventHandler(btnSearch_Click);
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

        private void dgRoles_ItemDataBound(object source, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {

                    ImageButton ibdelete = (ImageButton)e.Item.FindControl("imageDelete");

                    ibdelete.Attributes.Add("onclick", "return confirm('This item will be cancel delegation. Are you sure ?');");
                }
            }
            catch (GDCException gdcEx)
            {
                WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
            }
            catch (Exception ex)
            {
                WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
            }
        }

        public void dgRoles_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            if (e.CommandName == "btnDelete")
            {
                string itemId = e.Item.Cells[0].Text;
                IUser iuser = AppContainer.Instance[ServiceConst.UserService] as IUser;

                BEGDC.CC.Entity.UserRole role = iuser.GetUserRoleByID(Convert.ToInt32(itemId));

                //Clear Cache
                if (role.DelegateEndDate == null) return;
                BEGDC.CC.BL.Workflow.CCPrincipal.RemovePrincipal(role.DelegateUser.NameEN);

                role.DelegateUser = null;
                role.DelegateStartDate = Nullables.NullableDateTime.Default;
                role.DelegateEndDate = Nullables.NullableDateTime.Default;
                role.IsEnabled = false;
                iuser.SaveUserRole(role);

                // Write Log
                IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as IUtility;
                CCIdentity id = this.User.Identity as CCIdentity;
                BEGDC.CC.Entity.OperationLog log = new BEGDC.CC.Entity.OperationLog();
                log.Module = "UserManagement";
                log.OperationType = "Delegation Role";
                Employee emp = new Employee();
                emp.Id = id.UserInfo.Id;
                log.Employee = emp;
                log.Time = System.DateTime.Now;
                log.Description = "[Delegation Role:Cancel Delegation";
                utility.SaveOperationLog(log);

                this.BindData();
            }
            else
            {
                this.BindData();
            }


        }

        void btnSearch_Click(object sender, EventArgs e)
        {
            using (var dc = new ASBCC.Database.EntityFramework.CCEntities())
            {
                ASBCC.Database.EntityFramework.Employee emp = dc.Employees.First(em => em.NameEN == this.SearchStaff.EmployeeName);
                this._SelectedUser = emp.EmployeeNo;
                this.SearchStaff.EmployeeID = emp.EmployeeNo;
            }
            this.BindData();
        }

    }
}
